/**
 * ws client reconnect example
 * Reconect handle:
 * - WEBSOCKET_EVENT_FINISH
 * - WEBSOCKET_EVENT_DISCONNECTED
 * - WEBSOCKET_EVENT_CLOSED
 * - WEBSOCKET_EVENT_ERROR
 */

#include <stdio.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "protocol_examples_common.h"
#include "esp_crt_bundle.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/event_groups.h"

#include "esp_log.h"
#include "esp_websocket_client.h"
#include "esp_event.h"
#include <cJSON.h>

#include "ws_client.h"

static const char *TAG = "main";

uint8_t sensor_data[512] = {0x11, 0x22, 0x33};

uint8_t counter = 0;

static void ws_rx_data_handle(uint8_t opcode, const uint8_t *data, uint16_t len)
{
    if (opcode == 0x01) // text
    {
        printf("%d, %s\n", len, (char *)data);

        cJSON *root = cJSON_Parse((char *)data);
        if (root)
        {
            cJSON *ws_url = cJSON_GetObjectItem(root, "ws_url");
            if (ws_url)
            {
                ESP_LOGW(TAG, "Json={'ws_url': '%s'}", ws_url->valuestring);
            }

            cJSON *ota_url = cJSON_GetObjectItem(root, "ota_url");
            if (ota_url)
            {
                ESP_LOGW(TAG, "Json={'ota_url': '%s'}", ota_url->valuestring);
            }

            cJSON_Delete(root);
        }
    }
}

static void sensor_data_task(void *arg)
{
    for (;;)
    {
        memset(sensor_data, 0, sizeof(sensor_data));
        if(counter++ > 100)
            counter = 0;
        int len = sprintf((char *)sensor_data, "{\"payload\": {\"process\":%d,\"result\": \"success\"}}", counter);
        ws_client_send(sensor_data, len);
        vTaskDelay(pdMS_TO_TICKS(100));
    }
    vTaskDelete(NULL);
}

void app_main(void)
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("websocket_client", ESP_LOG_DEBUG);
    esp_log_level_set("transport_ws", ESP_LOG_DEBUG);
    esp_log_level_set("trans_tcp", ESP_LOG_DEBUG);

    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    ESP_ERROR_CHECK(example_connect());

    ws_client_setup();
    ws_client_start();
    ws_set_data_callback(ws_rx_data_handle);

    xTaskCreate(sensor_data_task, "sensor_data_task", 4096, NULL, 10, NULL);
}
